using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using DataService.Helper;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using OpcuaClient.Model;

namespace OpcuaClient.Service
{
    public class AppService
    {
        public static LogHelper LogHelper { get; set; } = new LogHelper();
        public static App App { get; set; }
        static ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();
        static IConfigurationRoot configRoot;
        public AppService()
        {
            cfgBuilder.AddJsonFile("AppSetting.json", optional: true, reloadOnChange: true);
            configRoot = cfgBuilder.Build();
            App = configRoot.Get<App>();
            DbSettings = App.DbSettings;
            CollectServers = App.CollectServers == null ? new List<CollectServer>() : App.CollectServers;
        }
        /// <summary>
        ///数据库连接配置
        /// </summary>
        public static List<DbSetting> DbSettings { get; set; }
        /// <summary>
        /// 数据采集服务器
        /// </summary>
        public static List<CollectServer> CollectServers { get; set; }

        // 多个节点name格式 ：["key:key1"]
        public static string GetSettingString(string key)
        {
            return configRoot[key];
        }
        // 多个节点,通过.GetSection("key")["key1"]获取
        public static IConfigurationSection GetSection(string key)
        {
            return configRoot.GetSection(key);
        }
        /// <summary>
        /// 获取一台服务器
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static CollectServer GetServer(string name)
        {
            CollectServer server = App.CollectServers.FirstOrDefault(m => m.Name == name || m.Code == name);
            return server;
        }
        /// <summary>
        /// 添加数据采集服务器
        /// </summary>
        /// <param name="server"></param>
        public static void SaveServer()
        {
            StreamWriter streamWriter = new StreamWriter("AppSetting.json");
            streamWriter.WriteLine(JsonConvert.SerializeObject(App));
            streamWriter.Close();
        }
    }
}
